﻿using Aliyun.OSS;
using Microsoft.Extensions.Caching.Memory;
using OA.Core;
using OA.Core.DataAccessHelper;
using OA.Core.Helper;
using OA.Model;
using OA.Model.Mapper;
using OA.Model.MyAttribute;
using OA.Model.View;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using OA.Core.Other;
using OA.Core.Oss;
using OA.Model.Api;
using System.Net;
using System.Text;
using OA.Model.DB;
using OA.Model.Other;
using OA.Core.Model;
using OA.Model.Result;

namespace OA.BLL
{
    public class CVoucher : CBase
    {
        public static Voucher GetVoucherByID(int customFormID, int formID)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            var info = dal.GetByID<Voucher>(formID);
            info.CustomFormID = customFormID;
            return info;
        }

        public static string GetLastNO(int customFormID)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            Expression<Func<Voucher, bool>> where = m => true;
            Func<SimpleVoucher, int> order = m => m.ID;
            var list = dal.GetPageList<Voucher, SimpleVoucher, int>(where, SimpleVoucher.NOMap, order, false);

            if (list.Count > 0) return list[0].No;
            return string.Empty;
        }

        public static List<SimpleVoucher> GetVoucherListByID(int customFormID, int pageSize, int pageIdx, Expression<Func<Voucher, bool>> expression, Expression<Func<Voucher, SimpleVoucher>> map, Func<SimpleVoucher, int> orderExpression,bool asc, ref int totalCount)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            var result= dal.GetPageList<Voucher, SimpleVoucher, int>(pageSize, pageIdx, expression, map, orderExpression, asc, ref totalCount);
            result.ForEach(m => m.CustomFormID = customFormID);
            return result;
        }

        public static List<SimpleVoucher> GetVoucherListByID(int customFormID, int pageSize, int pageIdx, Expression<Func<Voucher, bool>> expression, Expression<Func<Voucher, SimpleVoucher>> map, Func<SimpleVoucher, int> orderExpression, bool asc)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            var result = dal.GetPageList<Voucher, SimpleVoucher, int>(pageSize, pageIdx, expression, map, orderExpression, asc);
            result.ForEach(m => m.CustomFormID = customFormID);
            return result;
        }



        public static void UpdateVoucherByID(Voucher infoVoucher, int customFormID)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            dal.Update<Voucher>(infoVoucher);
            dal.Save();
        }

        public static void AddVoucher(Voucher infoVoucher, int customFormID)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            dal.Add<Voucher>(infoVoucher);
            dal.Save();
        }

        public static void DeleteVoucherByID(int customFormID, int formID)
        {
            VoucherMapper voucherMapper = new VoucherMapper();
            var dal = DataAccessor.Create<VoucherDbContext>();
            dal.ChangeMappingTable(typeof(Voucher), voucherMapper, customFormID);
            dal.Delete<Voucher>(new Voucher() { ID = formID });
            dal.Save();
        }

   
        public void Map(Voucher info, CustomForm infoCustomForm, IMemoryCache _cache)
        {
            CacheHelper cacheHelper = new CacheHelper(_cache);
            List<Department> listDepartment = cacheHelper.GetDepartments();
            List<Position> listPosition = cacheHelper.GetPositions();
            List<Employee> listEmployee = cacheHelper.GetEmployees();
            List<VEmployeePosition> listEmployeePosition = cacheHelper.GetVEmployeePositions();
            this.Map(info, infoCustomForm, listDepartment, listPosition, listEmployee, listEmployeePosition, _cache);
        }

        public static object @Lock = new object();
        private static Dictionary<int, string> dicNo = new Dictionary<int, string>();
        public static string GetBills(int customFormID)
        {
            lock(@Lock)
            {
                try
                {
                    using (var dbcontext = new MyDbContext())
                    {
                        string lastNO = string.Empty;
                        if (dicNo.ContainsKey(customFormID))
                        {
                            lastNO = dicNo[customFormID];
                        }
                        else
                        {
                            lastNO = CVoucher.GetLastNO(customFormID);
                            dicNo.Add(customFormID, lastNO);
                        }

                        CustomForm customForm = dbcontext.CustomForm.Where(m => m.ID == customFormID).FirstOrDefault();
                        string prefix = customForm.NoPrefix;
                        if (string.IsNullOrWhiteSpace(lastNO)) return prefix + "00001";
                        if (!lastNO.StartsWith(prefix))
                        {
                            dicNo[customFormID] = prefix + "00001";
                            return prefix + "00001";
                        }
                        else
                        {
                            string temp = lastNO.Replace(prefix, "");
                            int number = 0;
                            if (!Int32.TryParse(temp, out number))
                            {
                                dicNo[customFormID] = prefix + "00001";
                                return prefix + "00001";
                            }
                            else
                            {
                                number = number + 1;
                                dicNo[customFormID] = prefix + number.ToString("D5");
                                return prefix + number.ToString("D5");
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                   return string.Empty;
                }
                
            }            
        }

        public bool CheckPosition(int position,List<Filter> list)
        {
            return true;
        }


        public void Map(Voucher info, CustomForm infoCustomForm, List<Department> listDepartment, List<Position> listPosition, List<Employee> listEmployee, List<VEmployeePosition> listEmployeePosition, IMemoryCache _cache)
        {

            CacheHelper cacheHelper = new CacheHelper(_cache);
            var baseConfig = cacheHelper.GetConfig<BaseConfig>();
            Position infoPosition = listPosition.Where(m => m.ID == info.PositionID).FirstOrDefault();
            if (infoPosition != null) { info.PositionName = infoPosition.Name; }

            Employee sponsorEmployee = listEmployee.Where(m => m.EmpID == info.Sponsor).FirstOrDefault();
            if (sponsorEmployee != null) { info.SponsorName = sponsorEmployee.EmpName; }
            info.DepartmentName = CDepartment.GetFullDepartmentNameByID(info.DepartmentID, listDepartment);


            #region 获取审批流
             
            List<ApprovalItem> approvalItems = new List<ApprovalItem>();
            if (info.ApprovalID > 0) { approvalItems = this.dbContextFactory.DbContext.ApprovalItem.Where(m => m.ApprovalID == info.ApprovalID).ToList(); }
            if (info.Status == 4)//审批完成的，直接读审批数据
            {
                info.ApprovalItems = approvalItems;
            }
            else
            {
                CApproval objApproval = new CApproval(_cache);
                ApprovalResult approvalResult = objApproval.GetApprovalResult(listDepartment, listPosition, listEmployee, listEmployeePosition, infoCustomForm, info, approvalItems, baseConfig.PositionLevel);
                info.ApprovalItems = approvalResult.approvalItems;                
            }

            #endregion


            #region 替换扩展字段中的部门，岗位，职员信息
            List< ExtendField> extendFields = null;
            if (!string.IsNullOrWhiteSpace(info.CustomFormContent))
            {
                extendFields = JsonHelper.DeserializeList<ExtendField>(info.CustomFormContent);
            }

            Dictionary<string, string> extendInfo = new Dictionary<string, string>();


            if (!string.IsNullOrWhiteSpace(info.Extension))
            {
                extendInfo = JsonHelper.DeserializeObj<Dictionary<string, string>>(info.Extension);
            }

            if (extendInfo != null && extendInfo.Count > 0)
            {
                var employees = extendFields.Where(m => m.Type == (int)TagEnum.Employee || m.Type == (int)TagEnum.Employee2).ToList();
                var departments = extendFields.Where(m => m.Type == (int)TagEnum.Department || m.Type == (int)TagEnum.Department2).ToList();
                var positions = extendFields.Where(m => m.Type == (int)TagEnum.Position|| m.Type == (int)TagEnum.Position2).ToList();
                var companys = extendFields.Where(m => m.Type == (int)TagEnum.RelatedCompany || m.Type == (int)TagEnum.Supplier || m.Type == (int)TagEnum.Customer || m.Type == (int)TagEnum.Contact || m.Type == (int)TagEnum.Product).ToList();
                var tables = extendFields.Where(m => m.Type == (int)TagEnum.Table).ToList();
                var references = extendFields.Where(m => m.Type == (int)TagEnum.Reference).ToList();

                foreach (var item in references)
                {
                    if (extendInfo.ContainsKey(item.Attribute))
                    {
                        string referenceInfo = extendInfo[item.Attribute];

                        if (!string.IsNullOrWhiteSpace(referenceInfo))
                        {
                            var reference = JsonHelper.DeserializeObj<SimpleReferences>(referenceInfo);
                            if (reference != null)
                            {
                                extendInfo[item.Attribute] = reference.No + ":" + reference.Title;
                            }
                        }
                    }
                }

                foreach (var item in companys)
                {
                    if (extendInfo.ContainsKey(item.Attribute))
                    {
                        string companyInfo = extendInfo[item.Attribute];

                        if (!string.IsNullOrWhiteSpace(companyInfo))
                        {
                            var company = JsonHelper.DeserializeObj<ProductReferences>(companyInfo);
                            if (company != null)
                            {
                                extendInfo[item.Attribute] = company.Name;
                            }
                        }
                    }
                }

                foreach (var item in employees)
                {
                    if (extendInfo.ContainsKey(item.Attribute))
                    {
                        string empID = extendInfo[item.Attribute];
                        
                        if (!string.IsNullOrWhiteSpace(empID))
                        {
                            var employee = listEmployee.Where(m => m.EmpID == empID).FirstOrDefault();
                            if (employee != null)
                            {
                                extendInfo[item.Attribute] = JsonHelper.SerializeObject(new SimpleEmpInfo() { EmpID = empID, Name = employee.EmpName });
                            }
                        }
                    }
                }

                foreach (var item in departments)
                {
                    if (extendInfo.ContainsKey(item.Attribute))
                    {
                        int departmentID;
                        if (Int32.TryParse(extendInfo[item.Attribute], out departmentID))
                        {
                            string departmentName = CDepartment.GetFullDepartmentNameByID(departmentID, listDepartment);
                            extendInfo[item.Attribute] = JsonHelper.SerializeObject(new SimpleOtherInfo() { ID = departmentID.ToString(), Name = departmentName });
                        }
                    }
                }

                foreach (var item in positions)
                {
                    if (extendInfo.ContainsKey(item.Attribute))
                    {
                        string positionValue = extendInfo[item.Attribute];
                        int positionID = 0;
                        if (Int32.TryParse(positionValue, out positionID))
                        {
                            Position position = listPosition.Where(m => m.ID == positionID).FirstOrDefault();
                            if (position != null)
                            {
                                var departmentName = CDepartment.GetFullDepartmentNameByID(position.DepartmentID, listDepartment);
                                extendInfo[item.Attribute] = JsonHelper.SerializeObject(new SimpleOtherInfo() { ID = positionID.ToString(), Name = departmentName + position.Name });
                            }
                        }
                    }
                }

                foreach (var item in tables)
                {
                    if(extendInfo.ContainsKey(item.Attribute))
                    {
                        string tableResult = extendInfo[item.Attribute];
                        List<Dictionary<string,string>> tableInfo= JsonHelper.DeserializeList<Dictionary<string, string>>(tableResult);
                        string tableTemplate = item.DefaultValue;
                        var tableExtendFields = JsonHelper.DeserializeList<ExtendField>(tableTemplate);
                        var tableEmployees = tableExtendFields.Where(m => m.Type == (int)TagEnum.Employee|| m.Type == (int)TagEnum.Employee2).ToList();
                        var tableDepartments = tableExtendFields.Where(m => m.Type == (int)TagEnum.Department|| m.Type == (int)TagEnum.Department2).ToList();
                        var tablePositions = tableExtendFields.Where(m => m.Type == (int)TagEnum.Position|| m.Type == (int)TagEnum.Position2).ToList();
                        var tableReferences = tableExtendFields.Where(m => m.Type == (int)TagEnum.Reference).ToList();
                        var tableCompanys = tableExtendFields.Where(m => m.Type == (int)TagEnum.RelatedCompany || m.Type == (int)TagEnum.Supplier || m.Type == (int)TagEnum.Customer || m.Type == (int)TagEnum.Contact || m.Type == (int)TagEnum.Product).ToList();
                         
                        foreach (var tr in tableInfo)
                        {
                            foreach (var item2 in tableCompanys)
                            {
                                if (tr.ContainsKey(item2.Attribute))
                                {
                                    string companyInfo = tr[item2.Attribute];

                                    if (!string.IsNullOrWhiteSpace(companyInfo))
                                    {
                                        var company = JsonHelper.DeserializeObj<ProductReferences>(companyInfo);
                                        if (company != null)
                                        {
                                            tr[item2.Attribute] = company.Name;
                                        }
                                    }
                                }
                            }

                            foreach (var item2 in tableReferences)
                            {
                                if (tr.ContainsKey(item2.Attribute))
                                {
                                    string referenceInfo = tr[item2.Attribute];
                                    if (!string.IsNullOrWhiteSpace(referenceInfo))
                                    {
                                        var reference = JsonHelper.DeserializeObj<SimpleReferences>(referenceInfo);
                                        if (reference != null)
                                        {
                                            tr[item2.Attribute] = reference.No + ":" + reference.Title;
                                        }
                                    }
                                }
                            }

                            foreach (var item2 in tableEmployees)
                            {
                                if (tr.ContainsKey(item2.Attribute))
                                {
                                    string empID = tr[item2.Attribute];
                                    if (!string.IsNullOrWhiteSpace(empID))
                                    {
                                        var employee = listEmployee.Where(m => m.EmpID == empID).Select(m=>new { m.EmpID,m.EmpName}).FirstOrDefault();
                                        if (employee != null)
                                        {
                                            tr[item2.Attribute] = JsonHelper.SerializeObject(employee);
                                        }
                                    }
                                }
                            }

                            foreach (var item2 in tableDepartments)
                            {
                                if (tr.ContainsKey(item2.Attribute))
                                {
                                    int departmentID;
                                    if (Int32.TryParse(tr[item2.Attribute], out departmentID))
                                    {
                                        tr[item2.Attribute] = CDepartment.GetFullDepartmentNameByID(departmentID, listDepartment);
                                    }
                                }
                            }

                            foreach (var item2 in tablePositions)
                            {
                                if (tr.ContainsKey(item2.Attribute))
                                {
                                    string positionValue = tr[item2.Attribute];
                                    int positionID = 0;
                                    if (Int32.TryParse(positionValue, out positionID))
                                    {
                                        Position position = listPosition.Where(m => m.ID == positionID).FirstOrDefault();
                                        if (position != null)
                                        {
                                            var departmentName = CDepartment.GetFullDepartmentNameByID(position.DepartmentID, listDepartment);
                                            tr[item2.Attribute] = $"{departmentName} {position.Name}";
                                        }
                                    }
                                }
                            }
                        }                       

                        extendInfo[item.Attribute] = JsonHelper.SerializeObject(tableInfo);
                    }
                    
                }

            }

            info.Result = extendInfo;
            #endregion

        }


        public static string CreatePdf(BaseConfig baseConfig, OssConfig config,int voucherID)
        {
            return string.Empty;
            //using (var dbContext = new MyDbContext())
            //{
            //    var voucher=  dbContext.Voucher.Where(m => m.ID == voucherID).FirstOrDefault();
            //    if (voucher == null) return string.Empty;
            //    var customForm= dbContext.CustomForm.Where(m => m.ID == voucher.CustomFormID).FirstOrDefault();
            //    string myUrl = baseConfig.Url;                
            //    if (!myUrl.EndsWith("/"))
            //    {
            //        myUrl = myUrl + "/";
            //    }
            //    string url = myUrl + $"Home/Show?type=launched&id={voucherID}&token={baseConfig.Token}";
            //    HtmlToPdf converter = new HtmlToPdf();
            //    converter.Options.PdfPageSize = PdfPageSize.A4;
            //    if (customForm.PdfPageOrientation == 2)
            //    {
            //        converter.Options.PdfPageOrientation = PdfPageOrientation.Landscape;
            //        converter.Options.WebPageWidth = 1380;
            //    }
            //    else
            //    {
            //        converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            //        converter.Options.WebPageWidth = 1024;
            //    }

            //    converter.Options.WebPageHeight = 0;
            //    PdfDocument doc = converter.ConvertUrl(url);                
            //    var client = new OssClient(config.Endpoint, config.AccessKeyId, config.AccessKeySecret);
            //    string key = $"PDF/{customForm.ID}/{voucher.No}.pdf";
            //    MemoryStream ms = new MemoryStream();
            //    doc.Save(ms);
            //    ms.Seek(0, SeekOrigin.Begin);
            //    client.PutObject(config.BucketName, key, ms);
            //    doc.Close();
            //    return $"https://{config.BucketName}.{config.Endpoint}/{key}";
            //}
            
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="infoVoucher"></param>
        /// <param name="list"></param>
        /// <param name="DicExtend">初始值</param>
        public static Dictionary<string, ExtendField> GetExtendFieldInfo(MyDbContext dbContext, VoucherInfo infoVoucher, List<ExtendField> list,Dictionary<string, string> DicExtend,List<Department> departments,List<VPosition> positions,List<VEmployeePosition> vep, IMemoryCache _cache)
        {
            Dictionary<string, ExtendField> dic = new Dictionary<string, ExtendField>();
            foreach (var item in list)//遍历单据项
            {
                dic.Add(item.Attribute, item);

                if (DicExtend!=null&&DicExtend.ContainsKey(item.Attribute))
                {
                    item.Value = DicExtend[item.Attribute];
                }
                else
                {
                    item.Value = "";
                }
                item.Value = item.Value ?? "";
                item.Text = item.Text ?? "";
                item.Values = item.Values ?? "";
                #region 初始化数据
                if (!string.IsNullOrWhiteSpace(item.Value))
                {
                    if (item.Type == 15 || item.Type == 16)//单个图片和文件
                    {
                        item.Files = new List<string>() { item.Value };
                    }
                    else if (item.Type == 17 || item.Type == 18)//多个图片和文件
                    {
                        item.Files = JsonHelper.DeserializeList<string>(item.Value);
                    }
                    else if (item.Type == 40 || item.Type == 41 || item.Type == 42 || item.Type == 43||item.Type==44)//引用公司及联系人
                    {
                        var otherInfo = JsonHelper.DeserializeObj<SimpleOtherInfo>(item.Value);
                        item.Value = "";
                        if (otherInfo != null)
                        {
                            item.Text = otherInfo.Name;
                            item.Value = otherInfo.ID.ToString();
                        }

                    }
                    else if (item.Type == 22)//职员
                    {
                        var otherInfo = JsonHelper.DeserializeObj<SimpleEmpInfo>(item.Value);
                        if (otherInfo != null)
                        {
                            item.Value = JsonHelper.ToBase62<SimpleEmpInfo>(otherInfo);
                            item.Text = otherInfo.Name;
                        }
                    }                    
                    else if (item.Type == 30|| item.Type == 31)//单据引用
                    {
                        item.Refs = JsonHelper.DeserializeList<SimpleApproval>(item.Value);
                        if (item.Refs == null || item.Refs.Count == 0)
                        {
                            item.Refs = new List<SimpleApproval>();
                            item.Refs.Add(new SimpleApproval());
                        }
                    }                    
                }
                else if (item.Type == 17 || item.Type == 18)
                {
                    item.Files = new List<string>();
                }
                else if (item.Type == 30 || item.Type == 31)
                {
                    item.Refs = new List<SimpleApproval>();
                }
                if (item.Type == 15)
                {
                    item.Max = 1;
                }
                

                #endregion

                #region 单据项数据源处理
                if ((item.Type == 3 || item.Type == 25 || item.Type == 4 || item.Type == 5) && !string.IsNullOrWhiteSpace(item.Values)) //下拉+单选+多选择
                {
                    List<MySelectItem> List = new List<MySelectItem>();
                    if (item.Values == "0")
                    {
                        List = new List<MySelectItem>() { new MySelectItem() { name = "请选择", id = "0" } };
                    }
                    else if (item.Values.StartsWith("http://") || item.Values.StartsWith("https://"))
                    {
                        try
                        {
                            WebClient wc = new WebClient();
                            wc.Encoding = Encoding.UTF8;
                            string result = wc.DownloadString(item.Values);
                            item.ThirdPartyDataSource = result;
                            List = JsonHelper.DeserializeList<MySelectItem>(result);
                        }
                        catch (Exception ex)
                        {
                            List = new List<MySelectItem>() { new MySelectItem() { name = ex.Message, id = "0" } };
                        }
                    }
                    else if (item.Values.ToLower().StartsWith("sql:"))
                    {
                        try
                        {
                            var result = "[" + dbContext.Database.SqlQuery<StringBase>(item.Values.Substring(4).Replace("'", "") + " FOR JSON AUTO, INCLUDE_NULL_VALUES,WITHOUT_ARRAY_WRAPPER", null).FirstOrDefault() + "]";
                            List = JsonHelper.DeserializeList<MySelectItem>(result);
                        }
                        catch (Exception ex)
                        {
                            List = new List<MySelectItem>() { new MySelectItem() { name = ex.Message, id = "0" } };
                        }
                    }
                    else
                    {
                        List = item.Values.Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries).ToList().Select(m => new MySelectItem() { name = m, id = m }).ToList();
                    }

                    for (int i = 0; i < List.Count; i++)
                    {
                        if (item.Type == 4)//单选
                        {
                            if (item.Value == List[i].id)
                            {
                                List[i].Checked = true;
                            }
                        }
                        else if (item.Type == 5)//多选择
                        {
                            if (item.Value == List[i].id || item.Value.StartsWith(List[i].id + ",") || item.Value.IndexOf("," + List[i].id + ",") != -1 || item.Value.EndsWith("," + List[i].id))
                            {
                                List[i].Checked = true;
                            }
                        }
                        else if (List[i].id == item.Value)//下拉
                        {
                            item.Text = List[i].name;
                        }
                    }
                    if(!infoVoucher.DicDataScore.ContainsKey(item.Attribute))
                    {
                        infoVoucher.DicDataScore.Add(item.Attribute, List);
                    }
                    
                }
                else if (item.Type == 22)//员工
                {
                    if (!string.IsNullOrWhiteSpace(item.Value))
                    {

                        if (!string.IsNullOrWhiteSpace(item.Value))
                        {
                            var employee = vep.Where(m => m.EmpID == item.Value).FirstOrDefault();
                            if (employee != null)
                            {
                                item.Text = employee.EmpName;
                                List<KeyValue> departmentPath = CDepartment.GetDepartmentPath(_cache, employee.DepartmentID);
                                while (departmentPath.Count > 0)
                                {
                                    if (infoVoucher.Departments.Where(m => m.id == departmentPath[0].Value).FirstOrDefault() == null)
                                    {
                                        departmentPath.RemoveAt(0);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                item.Files = departmentPath.Select(m => m.Value.ToString()).ToList();//员工部门路径
                            }
                        }
                    }
                }
                else if (item.Type == 23)//部门
                {
                    int tempDepartment;
                    if (Int32.TryParse(item.Value, out tempDepartment))
                    {
                        List<KeyValue> departmentPath = CDepartment.GetDepartmentPath(_cache, tempDepartment);

                        while (departmentPath.Count > 0)
                        {
                            if (infoVoucher.Departments.Where(m => m.id == departmentPath[0].Value).FirstOrDefault() == null)
                            {
                                departmentPath.RemoveAt(0);
                            }
                            else
                            {
                                break;
                            }
                        }

                        item.Files = departmentPath.Select(m => m.Value.ToString()).ToList();
                        item.Text = string.Join(" ", departmentPath.Select(m => m.Text).ToList());

                    }

                }
                else if (item.Type == 24)//岗位
                {
                    if (infoVoucher.Positions == null || infoVoucher.Positions.Count == 0)
                    {
                        infoVoucher.Positions = new Dictionary<int, List<PositionInfo>>();
                        foreach (var department in departments)
                        {
                            var postions = positions.Where(m => m.DepartmentID == department.ID).Select(m => new PositionInfo { id = m.ID.ToString(), name = m.Name }).ToList();
                            if (postions.Count > 0)
                            {
                                infoVoucher.Positions.Add(department.ID, postions);
                            }
                            else
                            {
                                infoVoucher.Positions.Add(department.ID, new List<PositionInfo>());
                            }
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(item.Value))
                    {
                        int tempPositionID = 0;
                        if (Int32.TryParse(item.Value, out tempPositionID))
                        {
                            var position = positions.Where(m => m.ID == tempPositionID).FirstOrDefault();
                            if (position != null)
                            {
                                item.Text = position.Name;
                                List<KeyValue> departmentPath = CDepartment.GetDepartmentPath(_cache, position.DepartmentID);
                                while (departmentPath.Count > 0)
                                {
                                    if (infoVoucher.Departments.Where(m => m.id == departmentPath[0].Value).FirstOrDefault() == null)
                                    {
                                        departmentPath.RemoveAt(0);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                item.Files = departmentPath.Select(m => m.Value.ToString()).ToList();//部门路径
                            }
                        }
                    }
                }

                #endregion

            }

            return dic;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="info"></param>
        /// <param name="rule"></param>
        /// <param name="type">0：基础数据  1:表单数据</param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static bool VerifyItem(ExtendField info, ExtendField rule,int index, ref string errorMsg)
        {
            string tip = "基础信息 ";
            if(index > -1)
            {
                tip = $"表单数据第{index}项 ";
            }
            string value = info.Value ?? "";
            List<string> files = info.Files;
            if (files == null) { files = new List<string>(); }
            files = files.Where(m => !string.IsNullOrWhiteSpace(m)).ToList();
            List<SimpleApproval> refs = info.Refs;
            if (refs == null) { refs = new List<SimpleApproval>(); }
            if (rule.IsRequired && string.IsNullOrWhiteSpace(value))
            {
                errorMsg = tip + info.Name + " 不能为空";
                return false;
            }
            if(rule.Type==6&& !CommonHelper.IsEmail(info.Value))
            {
                errorMsg = tip + info.Name + " 必须为Email";
                return false;
            }

            if (rule.Type == 81 && !CommonHelper.IsPhone(info.Value))
            {
                errorMsg = tip + info.Name + " 必须为电话号码";
                return false;
            }

            if (rule.Type == 82 && !CommonHelper.IsIDCard(info.Value))
            {
                errorMsg = tip + info.Name + " 必须为正确的身份证号码";
                return false;
            }
            if (rule.Type == 83 && !CommonHelper.IsIDCard(info.Value))
            {
                errorMsg = tip + info.Name + " 必须为正确的网址";
                return false;
            }

            if(rule.Min>0)// 多图上传  多文件上传 多个单据引用
            {
                if (refs.Count == 0&& rule.Type==31)
                {
                    errorMsg = tip + info.Name + " 不能为空";
                    return false;
                }
                if (info.Files.Count==0&&(rule.Type == 17 || rule.Type == 18))
                {
                    errorMsg = tip + info.Name + " 不能为空";
                    return false;
                }
            }

            if(rule.Type==30||rule.Type==31)
            {
                info.Value = JsonHelper.SerializeObject(info.Refs.Where(m => m.CustomID > 0).ToList());
            }
            else if (rule.Type == 22&&!string.IsNullOrWhiteSpace(info.Value))//职员
            {
                info.Value = info.Value.FromBase62<string>();
            }            
            else if(rule.Type == 40 || rule.Type==41|| rule.Type == 42 || rule.Type == 43|| rule.Type==44)
            {
                info.Value = JsonHelper.SerializeObject(new { ID = info.Value, Name = info.Text });
            }  
            else if(rule.Type == 17 || rule.Type == 18)
            {
                info.Value = JsonHelper.SerializeObject(info.Files);
            }
            else if(rule.Type == 15||rule.Type == 16)
            {
                if(info.Files.Count>0)
                {
                    info.Value = info.Files[0];
                }
                else
                {
                    info.Value = "";
                }
            }
            return true;
        }

    }
}